using System;
using System.Collections.Generic;
using System.Linq;

namespace ImageProcessing.Common
{
    public class AntiClockWiseSorter
    {
        private int _x;
        private int _y;

        public List<InterestPoint> SortedList(IEnumerable<InterestPoint> listToSort)
        {
            var result = new List<InterestPoint>(listToSort);

            CalcMidPoint(listToSort);

            result.Sort(SortAntiClockWise);

            return result;
        }

        private void CalcMidPoint(IEnumerable<InterestPoint> listToSort)
        {
            int leftMostPoint = listToSort.Min(ip => ip.X);
            int rightMostPoint = listToSort.Max(ip => ip.X);
            
            int topMostPoint = listToSort.Max(ip => ip.Y);
            int bottomMostPoint = listToSort.Min(ip => ip.Y);

            _x = Math.Abs((leftMostPoint + rightMostPoint)/2);
            _y = Math.Abs((bottomMostPoint + topMostPoint)/2);
        }

        /// <summary>
        /// Points that are one the left and down are better
        /// http://stackoverflow.com/questions/6996942/c-sharp-sort-list-of-x-y-coordinates-clockwise
        /// </summary>
        /// <param name="firstPoint"></param>
        /// <param name="secondPoint"></param>
        /// <returns></returns>
        private int SortAntiClockWise(InterestPoint firstPoint, InterestPoint secondPoint)
        {
            //  Fetch the atans 
            double aTanA = Math.Atan2(firstPoint.Y - _y, firstPoint.X - _x);
            double aTanB = Math.Atan2(secondPoint.Y - _y, secondPoint.X - _x);

            //  Determine next point in Clockwise rotation 
            if (aTanA < aTanB) return -1;
            if (aTanB > aTanA) return 1;
            
            return 0;
        }
    }
}